package com.topcent.tioxyc.xxljob;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.topcent.tioxyc.constants.KeyConstant;
import com.topcent.tioxyc.mapper.Yy1KpiMapper;
import com.topcent.tioxyc.pojo.*;
import com.topcent.tioxyc.pojo.cc.PaymentTrackingjhdCC;
import com.topcent.tioxyc.pojo.vo.BCDesignAppVO;
import com.topcent.tioxyc.pojo.vo.CustomerPayVO;
import com.topcent.tioxyc.util.ApiClient;
import com.topcent.tioxyc.util.ConnmeUtils;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;

import java.math.BigDecimal;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: 陈百万
 * @date: 2025/5/13 10:50
 * @Description: 汇率SAP->jdy
 */
@Slf4j
@Component
public class CurrencyExchangeRateXxlJob {

    @Autowired
    private Yy1KpiMapper yy1KpiMapper;

    /**
     * SAP汇率
     *
     * @return
     */
    @XxlJob("GetSapExchangeRate")
    public void getSapExchangeRate() {
        String appId = "665fbebb30a77df3f2d3d47d";
        String entryId = "6660024157715a1b308dcee2";
        Header[] headers = new Header[3];
        String auth = KeyConstant.sapSALE001APIName + ":" + KeyConstant.sapSALE001APIPass;
        String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes());
        String authHeader = "Basic " + encodedAuth;
        headers[0] = new BasicHeader("Accept", "application/json");
        headers[1] = new BasicHeader("Authorization", authHeader);
        headers[2] = new BasicHeader("x-csrf-token", "Fetch");

        JSONObject entries = ApiClient.sendGetRequest("https://my200654-api.s4hana.sapcloud.cn/sap/opu/odata/sap/YY1_EXCHANGERATE_API_CDS/YY1_ExchangeRate_API", headers, null);
        String d = entries.getStr("d");
        JSONObject objects = JSONUtil.parseObj(d);
        String results = objects.getStr("results");
        JSONArray objectss = JSONUtil.parseArray(results);
        List<CurrencyExchangeRate> currencyExchangeRateList = JSONUtil.toList(objectss, CurrencyExchangeRate.class);
        // 转换日期格式并设置到ExchangeRateEffectiveDates字段
        for (CurrencyExchangeRate rate : currencyExchangeRateList) {
            rate.setExchangeRateEffectiveDates(parseSapDate(rate.getExchangeRateEffectiveDate()));
        }
        // 按ExchangeRateEffectiveDates降序排序（处理可能的null值）
        currencyExchangeRateList.sort(Comparator.comparing(
                CurrencyExchangeRate::getExchangeRateEffectiveDates,
                Comparator.nullsLast(Comparator.naturalOrder())
        ).reversed());

        // 获取本周一的开始时间和下周一的开始时间
        LocalDate today = LocalDate.now();
        LocalDate monday = today.with(DayOfWeek.MONDAY); // 获取本周一
        LocalDate nextMonday = monday.plusWeeks(1);      // 获取下周一

        ZonedDateTime mondayStart = monday.atStartOfDay(ZoneId.systemDefault());
        ZonedDateTime nextMondayStart = nextMonday.atStartOfDay(ZoneId.systemDefault());

        Instant mondayStartInstant = mondayStart.toInstant();
        Instant nextMondayStartInstant = nextMondayStart.toInstant();

        // 获取本周的数据（大于等于本周一且小于下周一）
        List<CurrencyExchangeRate> thisWeekRates = currencyExchangeRateList.stream()
                .filter(rate -> rate.getExchangeRateEffectiveDates() != null)
                .filter(rate -> {
                    Instant rateInstant = rate.getExchangeRateEffectiveDates().toInstant();
                    return !rateInstant.isBefore(mondayStartInstant) && rateInstant.isBefore(nextMondayStartInstant);
                }).toList();
        if (CollectionUtils.isNotEmpty(thisWeekRates)){
            List<CurrencyExchangeRateJdy> currencyExchangeRateJdyList = new ArrayList<>();
            Header[] header = ConnmeUtils.createHeaders();
            Map<String, Object> parameter = new HashMap<>();
            parameter.put("app_id", appId);
            parameter.put("entry_id", entryId);
            boolean fale = true;
            String zh = "";
            do {
                if (!zh.isEmpty()) {
                    parameter.put("data_id", zh);
                }
                parameter.put("limit", 100);
                String jsonSale = JSONUtil.toJsonStr(parameter);
                JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/list", header, jsonSale);
                String data = jdySale.getStr("data");
                JSONArray objectRate = JSONUtil.parseArray(data);
                List<CurrencyExchangeRateJdy> list = JSONUtil.toList(objectRate, CurrencyExchangeRateJdy.class);
                if (list.size() == 100) {
                    zh = list.getLast().get_id();
                } else {
                    fale = false;
                }
                currencyExchangeRateJdyList.addAll(list);
            } while (fale);

            // 统计本周数据的数量
            long thisWeekCount = currencyExchangeRateJdyList.stream()
                    .filter(jdyRate -> {
                        if (jdyRate.get_widget_1723450320496() == null) {
                            return false;
                        }
                        // 将Jdy中的DateTime转换为Instant进行比较
                        Instant jdyInstant = jdyRate.get_widget_1723450320496().toInstant();
                        return !jdyInstant.isBefore(mondayStartInstant) && jdyInstant.isBefore(nextMondayStartInstant);
                    }).count();
            // 判断条件修改为：本周数据不足5个时插入新数据
            if(thisWeekCount < 5){
                // 插入本周的数据
                for (CurrencyExchangeRate rate : thisWeekRates) {
                    CurrencyExchangeRateJdy jdyRate = new CurrencyExchangeRateJdy();
                    jdyRate.set_widget_1723450320496(rate.getExchangeRateEffectiveDates());
                    jdyRate.set_widget_1717568065854(rate.getSourceCurrency());
                    jdyRate.set_widget_1717568065857(rate.getExchangeRate());
                    jdyRate.set_widget_1723450320492(rate.getTargetCurrency());
                    Map<String, Object> parameterAdd = new HashMap<>();
                    parameterAdd.put("app_id", appId);
                    parameterAdd.put("entry_id", entryId);
                    parameterAdd.put("data", ConnmeUtils.convertEntityToMap(jdyRate));
                    jdyRate.set_id(null);
                    String jsonSaleAdd = JSONUtil.toJsonStr(parameterAdd);
                    JSONObject jsonObject = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/create", header, jsonSaleAdd);
                    System.out.println(jsonObject);
                }
            }
        }
    }

    private DateTime parseSapDate(String sapDateStr) {
        if (StringUtils.isNotBlank(sapDateStr)) {
            long timestamp = Long.parseLong(ConnmeUtils.extractTimestamp(sapDateStr));
            LocalDateTime ldt = ConnmeUtils.convertTimestampToLocalDateTime(timestamp);
            return new DateTime(ConnmeUtils.formatDateTime(ldt), DatePattern.NORM_DATETIME_FORMAT);
        }
        return null;
    }


    /**
     * 包材设计申请每日凌晨1点刷新
     *
     * @return
     */
    @XxlJob("pmDesignAppXxlJob")
    public String pmDesignApp() {
        Header[] headers = ConnmeUtils.createHeaders();
        List<BCDesignAppVO> bcDesignAppVOList = new ArrayList<>();
        String appId = "64ee9c37ee0a2c0007bc7afc";
        String entryId = "63edf3a123c2e70009100e2d";

        // 获取到包材设计申请进行中的数据
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("app_id", appId);
        parameter.put("entry_id", entryId);

        Map<String, Object> filter = new HashMap<>();
        filter.put("rel", "and");
        Map<String, Object> cond = new HashMap<>();
        cond.put("field", "flowState");
        cond.put("type", "flowstate");
        cond.put("method", "eq");
        List<Integer> values = new ArrayList<>();
        values.add(0);
        cond.put("value", values);
        List<Map<String, Object>> conds = new ArrayList<>();
        conds.add(cond);
        filter.put("cond", conds);
        parameter.put("filter", filter);

        boolean fale = true;
        String zh = "";
        do {
            if (!zh.isEmpty()) {
                parameter.put("data_id", zh);
            }
            parameter.put("limit", 100);
            String jsonSale = JSONUtil.toJsonStr(parameter);
            JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/list", headers, jsonSale);
            String data = jdySale.getStr("data");
            JSONArray objects = JSONUtil.parseArray(data);
            List<BCDesignAppVO> list = JSONUtil.toList(objects, BCDesignAppVO.class);
            if (list.size() == 100) {
                zh = list.getLast().get_id();
            } else {
                fale = false;
            }
            bcDesignAppVOList.addAll(list);
        } while (fale);

        // 查询进行中数据的审核流程状态。
        for (BCDesignAppVO bcDesignAppVO : bcDesignAppVOList) {
            Map<String, Object> parameterExam = new HashMap<>();
            parameterExam.put("instance_id", bcDesignAppVO.get_id());
            parameterExam.put("tasks_type", 1);
            String jsonSale = JSONUtil.toJsonStr(parameterExam);
            JSONObject jdySale = ApiClient.sendPostRequest("https://api.jiandaoyun.com/api/v5/workflow/instance/get", headers, jsonSale);
            JdyPurchaseOrder jdyPurchaseOrder = JSONUtil.toBean(jdySale, JdyPurchaseOrder.class);
            List<Task> taskList = jdyPurchaseOrder.getTasks();

            if (taskList != null && !taskList.isEmpty()) {
                // 1. 按创建时间降序排序（最新的在前）
                taskList.sort(Comparator.comparing(Task::getCreate_time).reversed());

                // 超七天确认设计次数
                int consecutiveOverdue = countConsecutiveOverdue(taskList);

                // 2. 查找最新的"设计人员确认接单"任务
                Optional<Task> latestDesignTaskOpt = taskList.stream()
                        .filter(task -> task.getFlow_id() == 20)
                        .findFirst();

                // 3. 处理找到的任务
                latestDesignTaskOpt.ifPresent(latestDesignTask -> {
                    DateTime createTime = latestDesignTask.getCreate_time();
                    if (createTime != null) {
                        // 1. 时间转换（保持原有时区处理逻辑）
                        LocalDateTime createLocalTime = LocalDateTime.parse(
                                createTime.toString(),
                                DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
                        ).atZone(ZoneOffset.UTC).toLocalDateTime();
                        LocalDateTime createTimePlus8h = createLocalTime.plusHours(8); // 转换为目标时区
                        LocalDateTime now = LocalDateTime.now(ZoneOffset.UTC); // 当前UTC时间

                        // 2. 过滤周末计算工作日天数
                        long workDays = 0;
                        LocalDate startDate = createTimePlus8h.toLocalDate();
                        LocalDate endDate = now.toLocalDate();

                        // 遍历从开始日期到结束日期的每一天
                        LocalDate currentDate = startDate;
                        while (!currentDate.isAfter(endDate)) {
                            DayOfWeek dayOfWeek = currentDate.getDayOfWeek();
                            // 排除周六（SATURDAY）和周日（SUNDAY）
                            if (dayOfWeek != DayOfWeek.SATURDAY && dayOfWeek != DayOfWeek.SUNDAY) {
                                workDays++;
                            }
                            currentDate = currentDate.plusDays(1); // 移至下一天
                        }

                        // 3. 后续处理（保持原逻辑）
                        log.info("设计人员确认接单任务已持续（排除周末）: {} 个工作日" , workDays);
                        bcDesignAppVO.set_widget_1751261983425(String.valueOf(workDays));
                        bcDesignAppVO.set_widget_1755584548172(String.valueOf(consecutiveOverdue));

                        Map<String, Object> parameterInster = new HashMap<>();
                        parameterInster.put("app_id", appId);
                        parameterInster.put("entry_id", entryId);
                        parameterInster.put("is_start_trigger", "true");
                        parameterInster.put("data_id", bcDesignAppVO.get_id());
                        bcDesignAppVO.set_id(null);
                        parameterInster.put("data", ConnmeUtils.convertEntityToMapNull(bcDesignAppVO));
                        String jsonSalee = JSONUtil.toJsonStr(parameterInster);
                        ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSalee);
                    }
                });
            }
        }
        return "修改了" + bcDesignAppVOList.size() + "条数据";
    }

    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    /**
     * 统计连续相邻且flow_id都是20（int类型）的任务超时次数
     */
    public int countConsecutiveOverdue(List<Task> sortedTaskList) {
        int count = 0;
        if (sortedTaskList == null || sortedTaskList.size() < 2) {
            return count;
        }

        // 遍历原始列表，检查相邻任务
        for (int i = 0; i < sortedTaskList.size() - 1; i++) {
            Task current = sortedTaskList.get(i);
            Task next = sortedTaskList.get(i + 1);

            // 核心：判断相邻两个任务的flow_id（int）是否都是20
            if (current.getFlow_id() != 20 || next.getFlow_id() != 20) {
                continue; // 只要有一个不是20，跳过
            }

            // 校验时间字段
            if (current.getCreate_time() == null || next.getFinish_time() == null) {
                continue;
            }

            try {
                // 解析时间并计算天数差
                LocalDateTime currentCreate = LocalDateTime.parse(current.getCreate_time().toString(), DATE_FORMATTER);
                LocalDateTime nextFinish = LocalDateTime.parse(next.getFinish_time().toString(), DATE_FORMATTER);
                long daysDiff = ChronoUnit.DAYS.between(nextFinish, currentCreate);

                if (daysDiff >= 7) {
                    count++;
                    System.out.printf("超时任务对：current=%s, next=%s, 相差%d天%n",
                            current.getTask_id(), next.getTask_id(), daysDiff);
                }
            } catch (Exception e) {
                System.err.println("时间解析失败：" + e.getMessage());
            }
        }

        return count;
    }

    /**
     *全系列产品报价每日一次刷新是否过期
     * @return
     */
    @XxlJob("updateOrderIsExpired")
    public String updateOrderIsExpired() {
        String appId = "64279a9442e2750008a7b0c1";
        String entryId = "64df0e0300d5ef000806a041";
        List<FullRangeProductVO> fullRangeProductVOS = new ArrayList<>();
        Header[] headers = ConnmeUtils.createHeaders();
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("app_id", appId);
        parameter.put("entry_id", entryId);

        Map<String, Object> filter = new HashMap<>();
        filter.put("rel", "and");
        Map<String, Object> cond = new HashMap<>();
        cond.put("field", "_widget_1692673057936");
        cond.put("type", "text");
        cond.put("method", "not_empty");
        List<Map<String, Object>> conds = new ArrayList<>();
        conds.add(cond);
        filter.put("cond", conds);
        parameter.put("filter", filter);

        boolean fale = true;
        String zh = "";
        do {
            if (!zh.isEmpty()) {
                parameter.put("data_id", zh);
            }
            parameter.put("limit", 100);
            String jsonSale = JSONUtil.toJsonStr(parameter);
            JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/list", headers, jsonSale);
            String data = jdySale.getStr("data");
            JSONArray objects = JSONUtil.parseArray(data);
            List<FullRangeProductVO> list = JSONUtil.toList(objects, FullRangeProductVO.class);
            if (list.size() == 100) {
                zh = list.getLast().get_id();
            } else {
                fale = false;
            }
            fullRangeProductVOS.addAll(list);
        } while (fale);

        // 遍历所有数据，判断是否过期
        for (FullRangeProductVO product : fullRangeProductVOS) {
            DateTime createTime = product.get_widget_1692673057936();
            if (createTime != null) {
                // 1. 时间转换（保持原有时区处理逻辑）
                LocalDateTime createLocalTime = LocalDateTime.parse(
                        createTime.toString(),
                        DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
                ).atZone(ZoneOffset.UTC).toLocalDateTime();
                LocalDateTime createTimePlus8h = createLocalTime.plusHours(8); // 转换为目标时区
                LocalDateTime now = LocalDateTime.now(ZoneOffset.UTC);
                FullRangeProductVO.FullRangeProductVOResult voResult = new FullRangeProductVO.FullRangeProductVOResult();
                voResult.set_id(product.get_id()); // id赋值
                if(now.isAfter(createTimePlus8h)){
                    // 已过期
                    voResult.set_widget_1756288080009("已过期");
                }else {
                    // 未过期
                    voResult.set_widget_1756288080009("未过期");
                }
                // 判断不为空
                if(StringUtils.isNotBlank(product.get_widget_1756288080009())){
                    if(product.get_widget_1756288080009().equals(voResult.get_widget_1756288080009())){
                        continue;
                    }
                }
                Map<String, Object> parameterInster = new HashMap<>();
                parameterInster.put("app_id", appId);
                parameterInster.put("entry_id", entryId);
                parameterInster.put("is_start_trigger", "true");
                parameterInster.put("data_id", voResult.get_id());
                voResult.set_id(null);
                parameterInster.put("data", ConnmeUtils.convertEntityToMapNull(voResult));
                String jsonSalee = JSONUtil.toJsonStr(parameterInster);
                ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSalee);
            }
        }
        return "订单过期状态更新完成，处理总数: " + fullRangeProductVOS.size();
    }

    /**
     * 交货单-收款跟踪数据对应数据
     *
     * @return
     */
    /**
     * 交货单-收款跟踪数据对应数据（仅更新 deliveryDocumentsEntity 相关字段）
     */
    @XxlJob("DeliveryNoteDate")
    public void deliveryNoteDate() {
        log.info("===== 开始执行交货单-收款跟踪数据更新任务（仅交货单相关赋值）=====");
        String appId = "669cb709a73cc1289c49800e";
        String entryId = "68db4c7420407efb3e3bc238";
        Header[] headers = ConnmeUtils.createHeaders();

        try {
            // 1. 获取核心数据（仅保留必要数据）
            Map<String, DeliveryDocumentsEntity> deliveryIndex = selectDeliveryData(); // 交货单数据（按销售单号分组）
            List<PaymentTrackingjhdCC> paymentList = getPaymentTrackingListFromApi(); // 收款跟踪数据
            log.info("获取数据完成：交货单分组{}个，收款跟踪数据{}条", deliveryIndex.size(), paymentList.size());

            // 2. 遍历收款跟踪数据，匹配并赋值更新
            int successCount = 0;
            for (PaymentTrackingjhdCC payment : paymentList) {
                try {
                    // 2.1 从唯一码提取销售单号（匹配依据）
                    String uniqueCode = payment.get_widget_1760327721440();
                    if (uniqueCode == null || uniqueCode.trim().isEmpty()) {
                        log.warn("收款跟踪数据_id:{} 唯一码为空，跳过", payment.get_id());
                        continue;
                    }
                    String salesNo = extractSalesNoFromUniqueCode(uniqueCode);
                    if (salesNo == null) continue;

                    // 2.2 匹配交货单数据
                    DeliveryDocumentsEntity delivery = deliveryIndex.get(salesNo);
                    if (delivery == null) continue;

                    // 2.3 仅赋值 deliveryDocumentsEntity 相关字段（严格对应之前 changeManey 逻辑）
                    assignOnlyDeliveryRelatedFields(payment, delivery);

                    // 2.4 更新到简道云
                    updatePaymentTrackingToJdy(headers, appId, entryId, payment);
                    successCount++;
                } catch (Exception e) {
                    log.error("更新收款跟踪数据_id:{} 失败", payment.get_id(), e);
                }
            }

            log.info("===== 任务执行完成 =====");
            log.info("成功更新{}条，未匹配/失败{}条", successCount, paymentList.size() - successCount);
        } catch (Exception e) {
            log.error("任务整体执行失败", e);
        }
    }

    /**
     * 仅赋值 deliveryDocumentsEntity 相关字段（完全对应之前 changeManey 中的映射）
     */
    private void assignOnlyDeliveryRelatedFields(PaymentTrackingjhdCC payment, DeliveryDocumentsEntity delivery) {
        // 工厂
        payment.set_widget_1759202420873(delivery.getPlant());
        // 交货单过账日期
        payment.set_widget_1759202420874(delivery.getActualGoodsMovementDate());
        // 交货单号
        payment.set_widget_1759203125361(delivery.getDeliveryDocument());
        // 交货金额（交易货币）
        payment.set_widget_1759203125365(delivery.getAmount1());
        // 交货单金额（集团货币）
        payment.set_widget_1759203125366(delivery.getAmount3());
        // 未收款余额（集团货币 = 交货金额 - 已回款CNY）
        BigDecimal amount3 = delivery.getAmount3() != null ? delivery.getAmount3() : BigDecimal.ZERO;
        BigDecimal receivedCny = payment.get_widget_1759203125371() != null ? payment.get_widget_1759203125371() : BigDecimal.ZERO;
        payment.set_widget_1759203125372(amount3.subtract(receivedCny));

        // 4. 应回款时间计算（依赖actualGoodsMovementDate，为null时不计算）
        Date actualGoodsMovementDate = delivery.getActualGoodsMovementDate();
        Date duePaymentDate = null;
        int js = Integer.parseInt(payment.get_widget_1759203125369()); // 计算天数
        if (actualGoodsMovementDate != null && js > 0) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(actualGoodsMovementDate);
            calendar.add(Calendar.DAY_OF_MONTH, js);
            duePaymentDate = calendar.getTime();
        }
        payment.set_widget_1759203125374(duePaymentDate); // 应回款时间

        // 5. 应回款月份计算（保持不变，依赖duePaymentDate）
        Date duePaymentMonthDate = null;
        if (duePaymentDate != null) {
            Calendar utcCalendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
            utcCalendar.setTime(duePaymentDate);
            utcCalendar.set(Calendar.DAY_OF_MONTH, 1);
            utcCalendar.set(Calendar.HOUR_OF_DAY, 0);
            utcCalendar.set(Calendar.MINUTE, 0);
            utcCalendar.set(Calendar.SECOND, 0);
            utcCalendar.set(Calendar.MILLISECOND, 0);
            duePaymentMonthDate = utcCalendar.getTime();
        }
        payment.set_widget_1759203125375(duePaymentMonthDate); // 应回款月份
    }

    /**
     * 从唯一码提取销售单号（兼容两种格式）
     */
    private String extractSalesNoFromUniqueCode(String uniqueCode) {
        String trimmed = uniqueCode.trim();
        String[] parts = trimmed.split("-");
        return parts.length > 0 ? parts[parts.length - 1].trim() : null;
    }

    /**
     * 简道云更新方法（不变）
     */
    private void updatePaymentTrackingToJdy(Header[] headers, String appId, String entryId, PaymentTrackingjhdCC payment) {
        String dataId = payment.get_id();
        if (dataId == null) throw new IllegalArgumentException("data_id为空");

        Map<String, Object> params = new HashMap<>();
        params.put("app_id", appId);
        params.put("entry_id", entryId);
        params.put("is_start_trigger", "true");
        params.put("data_id", dataId);

        String tempId = payment.get_id();
        payment.set_id(null);
        params.put("data", ConnmeUtils.convertEntityToMapNull(payment));
        ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, JSONUtil.toJsonStr(params));
        payment.set_id(tempId);
    }

    /**
     * 加载收款跟踪数据（仅改名，逻辑不变）
     */
    private List<PaymentTrackingjhdCC> getPaymentTrackingListFromApi() {
        log.info("加载收款跟踪表单数据");
        List<PaymentTrackingjhdCC> paymentList = new ArrayList<>();
        Header[] headers = ConnmeUtils.createHeaders();
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("app_id", "669cb709a73cc1289c49800e");
        parameter.put("entry_id", "68db4c7420407efb3e3bc238");
        boolean hasNext = true;
        String lastDataId = "";

        do {
            if (!lastDataId.isEmpty()) parameter.put("data_id", lastDataId);
            parameter.put("limit", 100);
            JSONObject response = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/list", headers, JSONUtil.toJsonStr(parameter));
            JSONArray dataArray = JSONUtil.parseArray(response.getStr("data"));
            List<PaymentTrackingjhdCC> batchList = JSONUtil.toList(dataArray, PaymentTrackingjhdCC.class);

            if (batchList.isEmpty()) {
                hasNext = false;
                continue;
            }

            paymentList.addAll(batchList);
            lastDataId = batchList.size() == 100 ? batchList.getLast().get_id() : "";
            hasNext = !lastDataId.isEmpty();
        } while (hasNext);

        return paymentList;
    }

    public Map<String, DeliveryDocumentsEntity> selectDeliveryData() {
        List<DeliveryDocumentsEntity> originalData = yy1KpiMapper.selecDeliveryDocumentsDatatAll();
        Map<String, DeliveryDocumentsEntity> resultMap = new HashMap<>();
        for (DeliveryDocumentsEntity data : originalData) {
            String groupKey = data.getReferenceSDDocument();
            if (groupKey == null || groupKey.trim().isEmpty()) {
                groupKey = "未知销售凭证";
            }
            if (!resultMap.containsKey(groupKey)) {
                DeliveryDocumentsEntity newEntity = new DeliveryDocumentsEntity();
                copyNonAmountFields(data, newEntity);
                newEntity.setAmount1(convertNullToZero(data.getAmount1()));
                newEntity.setNetAmount1(convertNullToZero(data.getNetAmount1()));
                newEntity.setAmount2(convertNullToZero(data.getAmount2()));
                newEntity.setNetAmount2(convertNullToZero(data.getNetAmount2()));
                newEntity.setAmount3(convertNullToZero(data.getAmount3()));
                newEntity.setNetAmount3(convertNullToZero(data.getNetAmount3()));
                resultMap.put(groupKey, newEntity);
            } else {
                DeliveryDocumentsEntity existingEntity = resultMap.get(groupKey);
                existingEntity.setAmount1(existingEntity.getAmount1().add(convertNullToZero(data.getAmount1())));
                existingEntity.setNetAmount1(existingEntity.getNetAmount1().add(convertNullToZero(data.getNetAmount1())));
                existingEntity.setAmount2(existingEntity.getAmount2().add(convertNullToZero(data.getAmount2())));
                existingEntity.setNetAmount2(existingEntity.getNetAmount2().add(convertNullToZero(data.getNetAmount2())));
                existingEntity.setAmount3(existingEntity.getAmount3().add(convertNullToZero(data.getAmount3())));
                existingEntity.setNetAmount3(existingEntity.getNetAmount3().add(convertNullToZero(data.getNetAmount3())));
            }
        }
        return resultMap;
    }

    private void copyNonAmountFields(DeliveryDocumentsEntity source, DeliveryDocumentsEntity target) {
        target.setDeliveryDocument(source.getDeliveryDocument());
        target.setReferenceSDDocument(source.getReferenceSDDocument());
        target.setActualGoodsMovementDate(source.getActualGoodsMovementDate());
        target.setConditionCurrency(source.getConditionCurrency());
        target.setSoldToParty(source.getSoldToParty());
        target.setBusinessPartnerName1(source.getBusinessPartnerName1());
        target.setYY1_divison_seller_DLH(source.getYY1_divison_seller_DLH());
        target.setSalesOfficeName(source.getSalesOfficeName());
        target.setPlant(source.getPlant());
    }

    private BigDecimal convertNullToZero(BigDecimal value) {
        return value == null ? BigDecimal.ZERO : value;
    }
}
